package com.originskyseed.platform.course.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.course.i18n.CourseResponseMsg;
import com.originskyseed.platform.course.model.CourseType;
import com.originskyseed.platform.course.service.ICourseService;
import com.originskyseed.platform.course.service.ICourseTypeService;
import com.originskyseed.platform.course.vo.request.CourseTypeRequestVO;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 课程类型表Controller类（OSI_COURSE_TYPE）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/courseType")
@BaseLocaleResource(localeFileName = "i18n_course")
public class CourseTypeController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CourseTypeController.class);

	@DubboReference
	private ICourseTypeService courseTypeService;

	@DubboReference
	private ICourseService courseService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseTypeList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CourseType>> courseTypeList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CourseType>> result = null;
		try {
			// 请求对象
			CourseTypeRequestVO requestVO = this.getParameterBean(CourseTypeRequestVO.class);

			// 分页查询
			BasePage<CourseType> page = new BasePage<CourseType>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseTypeService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<CourseType>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CourseType>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseTypeSave.json")
	public BaseResponseBody<CourseType> courseTypeSave(HttpServletRequest request) {
		BaseResponseBody<CourseType> result = null;
		try {
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			// 请求对象
			CourseType courseType = this.getParameterBean(CourseType.class);
			if (StringUtils.isNotBlank(courseType.getId())) {
				this.courseTypeService.updateByPrimaryKeySelective(courseType);
			} else {
				Integer prority = this.courseTypeService.selectPrority();
				if (prority == null) {
					courseType.setPrority(0);
				} else {
					courseType.setPrority(prority + 1);
				}
				// courseType.setCourseTypeId(createCourseTypeId());
				courseType.setIsTop(0);
				courseType.setCreatorId(userInfo.getId());
				courseType.setCreator(userInfo.getName());
				courseType.setIsDel(0);
				this.courseTypeService.insertSelective(courseType);
			}
			result = new BaseResponseBody<CourseType>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), courseType);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CourseType>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseTypeDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> courseTypeDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			for (String id : ids) {
				String courseId = this.courseService.selectCourseTypeExist(id);
				if (StringUtils.isNotBlank(courseId)) {
					return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.BIND_SOURCE_ERROR.getMsg()), null);
				}
			}
			this.courseTypeService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 根据id查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCourseTypeById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectCourseTypeById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			CourseType courseType = this.courseTypeService.selectByPrimaryKey(id);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), courseType);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCourseTypeList.json")
	public BaseResponseBody selectCourseTypeList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			CourseType courseType = this.getParameterBean(CourseType.class);

			// 查询列表
			List<CourseType> courseTypeList = this.courseTypeService.selectList(courseType);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), courseTypeList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 树形结构返回
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCourseTypeTree.json")
	public BaseResponseBody selectTaskCourseByPage(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 查询列表
			CourseType query = new CourseType();
			//query.setBelongPlatform(userInfo.getSourceSys());
			List<CourseType> courseTypeList = this.courseTypeService.selectList(query);
			JSONArray ary = new JSONArray();
			JSONObject obj;
			for (CourseType courseType : courseTypeList) {
				obj = new JSONObject();
				obj.put("id", courseType.getId());
				obj.put("code", "");
				obj.put("parentCode", "");
				obj.put("name", courseType.getName());
				ary.add(obj);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), ary);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer prority = this.courseTypeService.selectPrority();

			CourseType courseType = new CourseType();
			courseType.setId(id);
			courseType.setIsTop(1);
			courseType.setPrority(prority + 1);
			courseType.setUpdateTime(new Date());
			this.courseTypeService.updateIsTop(courseType);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);

			// 查询优先级
			CourseType query = this.courseTypeService.selectByPrimaryKey(id);
			Integer prority = query.getPrority();
			Map<String, Object> map = new HashMap<>();
			map.put("type", upOrDown);
			map.put("prority", prority);
			// 将另外一个升序或降序
			CourseType courseType = this.courseTypeService.selectCourseTypeByPriority(map);

			// 修改
			CourseType updateCourseType = new CourseType();
			updateCourseType.setId(id);

			if (courseType != null) {
				updateCourseType.setPrority(courseType.getPrority());
				courseType.setPrority(prority);
			} else {
				// 等于0是升序 1是降序
				if (upOrDown == 0) {
					updateCourseType.setPrority(prority + 1);
				} else {
					updateCourseType.setPrority(prority - 1);
				}
			}

			if (courseType != null) {
				this.courseTypeService.updatePrority(courseType, updateCourseType);
			} else {
				this.courseTypeService.updateByPrimaryKeySelective(updateCourseType);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 获取课程分类id
	 * 
	 * @return
	 * @throws Exception
	 */
	/*
	 * private String createCourseTypeId () throws Exception{ //获得当前时间戳 Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = formatter.format(currentTime); //生成随机数（随机数范围：1000到10000） int num = (int) (Math.random() * (10000 - 1000) + 1000); dateString += num;
	 * 
	 * // 判断id是否已存在 String courseTypeId = this.courseTypeService.selectCourseTypeId(dateString); if(StringUtils.isNotEmpty(courseTypeId)){ return createCourseTypeId(); }else { return dateString; } }
	 */

}